import weather
import message
import blue_connector
import threading
import time
import voice

connect = None
playing = False

def listenAlpha():
    global playing
    while True:
        s = connect.read()
        msgs = message.readMessage(s)
        for it in message.readMessage(s):
            # print (it['command'],it['parameter'])
            if(it['command']==message.PLAY_COMPLETION):
                print ("动作完毕")
                playing=False
        message.prettyPrint(s)
        time.sleep(0.01)
#主程序
if __name__ == '__main__':
    connect = blue_connector.BlueConnector()
    connect.send(message.handshake()) #握手
    message.prettyPrint(connect.read())

    wea = weather.Weather()
    print("成功建立天气获取器")
    listener = threading.Thread(target=listenAlpha)
    listener.start()
    
    while True:
        print ("开始聆听")
        result = voice.listen()
        if result == None:
            #voice.talk("没听清，请再说一次？")
            continue

        for cmd in result:
            if cmd == 'weather' or cmd == 'pm25' or cmd == 'houseWeather':
                s = wea.pretty(cmd)
                print(s)
                voice.talk(s)
                #做动作
                data = wea.getWeather(cmd)
                if(cmd == "weather" and data['text']=="晴"):
                    connect.send(message.execActList(b"goodday"))
                    playing = True
                elif (cmd == "pm25" and ( data['level'] != "优" or data['level'] != "良" )):
                    connect.send(message.execActList(b"badair"))
                    playing = True    

            elif cmd == 'dance':
                print('跳舞')
                connect.send(message.execActList(b"sweet and sour"))
                playing = True
            else :
                print(cmd)
                voice.talk("我现在还无法理解你说什么，抱歉！")

            while playing:
                #等待动作终结
                time.sleep(0.5)
            
                
        
            